package org.bl.chat.service;

import cn.hutool.core.bean.BeanUtil;
import org.bl.chat.common.exception.BusinessesException;
import org.bl.chat.dao.ChannelDao;
import org.bl.chat.model.po.ChannelDO;
import org.bl.chat.model.dto.ChannelSaveDTO;
import org.bl.chat.model.vo.ChannelVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class ChannelService {

    @Resource
    private ChannelDao channelDao;
    /**
     * 新增或修改频道。
     * 逻辑：如果 request.id 为空，则为新增；否则为修改。
     * @param request 频道保存请求参数 DTO
     * @return 保存后的 ChannelDO
     */
    public ChannelDO save(ChannelSaveDTO request) {

        ChannelDO channelDO;

        if (request.getId() == null || request.getId().isEmpty()) {
            // ============== 新增逻辑 ==============
            channelDO = new ChannelDO();
            channelDO.setName(request.getName());
            channelDO.setCreateTime(LocalDateTime.now());
            // updateTime 和 createTime 初始值相同
            channelDO.setUpdateTime(LocalDateTime.now());

        } else {
            // 1. 尝试从数据库中查找现有实体
            Optional<ChannelDO> optionalDO = channelDao.findById(request.getId());
            if (optionalDO.isPresent()) {
                channelDO = optionalDO.get();
                // 2. 更新需要修改的字段
                channelDO.setName(request.getName());
                channelDO.setUpdateTime(LocalDateTime.now());
            } else {
                // 如果 ID 存在但找不到对应实体，可根据业务选择抛出异常或作为新增处理
                throw new BusinessesException("频道ID不存在：" + request.getId());
            }
        }

        // 3. 调用 DAO 的 save 方法。Spring Data MongoDB 会根据 ID 自动判断是插入还是更新
        return channelDao.save(channelDO);
    }

    public List<ChannelVO> list() {
        List<ChannelDO> all = channelDao.findAll();
        return BeanUtil.copyToList(all, ChannelVO.class);
    }
}
